package com.wxy.web.security.authentication;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wxy.web.model.User;
import com.wxy.web.service.IMenuService;
import com.wxy.web.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {
    @Autowired
    IUserService userService;

    @Autowired
    IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username){
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(User::getUsername , username);
        User user = userService.getOne(userLambdaQueryWrapper);

        //user.setPassword(SecurityUtils.encryptPassword("123456"));
        //userService.updateById(user);

        if (user == null) {
            throw new UsernameNotFoundException("账号不存在");
        } else {
           // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
          //  user.setPassword(passwordEncoder.encode(user.getPassword()));
            return createJwtUser(user);
        }
    }

    private JwtUser createJwtUser(User user) {
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                getAuthorities(user.getId()),
                !user.getIsLockedout()
        );
    }

    private Collection<GrantedAuthority> getAuthorities(Integer userId){
        Collection<GrantedAuthority> authorities = new ArrayList<>();
//        List<MenuDTO> menus;
//        if (isadmin) {
//            menus = menuService.list();
//        } else {
//            menus = menuService.listByUserId(userId);
//        }
//        for (MenuDTO menu : menus){
//            if (menu.getPcode() != null && !menu.getPcode().equals("")) {
//                authorities.add(new SimpleGrantedAuthority(menu.getPcode()));
//            }
//            if (menu.getRelationCode() != null && !menu.getRelationCode().equals("")){
//                for (String code : menu.getRelationCode().split("\\|")){
//                    authorities.add(new SimpleGrantedAuthority(code));
//                }
//            }
//        }
        return authorities;
    }

}

